Sorting Band Names without articles


Posted by wayne201299 on 2023-10-02

DEMO

去除掉贅詞後,依英文字母由A到Z排序

實作

  1. 透過正則表示式將a、the、an替換成空字串再來sort

     function stripArticles(bandName) {
         return bandName.replace(/^(a |the |an )/i, "").trim();
     }
    
  2. 排序並插入ul中

     const sortedBands = stripBrands.sort((a, b) =>
         stripArticles(a) > stripArticles(b) ? 1 : -1
     );
    
     document.querySelector("#bands").innerHTML = sortedBands
         .map((band) => `<li>${band}</li>`)
         .join("");
    

知識點

  • document.querySelector("#bands")可以選中有id的element

#javascript







Related Posts

[ 筆記 ] DOM - 事件傳遞機制:捕獲與冒泡、事件代理

[ 筆記 ] DOM - 事件傳遞機制:捕獲與冒泡、事件代理

Day00

Day00

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段一:指定練習專案:STYLiSH)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段一:指定練習專案:STYLiSH)


Comments